

package com.tianyalei.zuul.demo.authserver.utils;



import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * jwt工具类
 *
 * @author ratel
 */

@Component
public class JwtUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());


    //加密秘钥
    private String secret ="f4e2e52034348f86b67cde581c0f9eb5[ratel]";
    //token有效时长，7天，单位秒
    private long expire = 604800;
    //token
    private String header;


    /**
     * 生成jwt token
     */
    public String generateToken(long userId) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId+"")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    public static void main(String[] args) {
        JwtUtils jwtUtils = new JwtUtils();
        String s = jwtUtils.generateToken(1001L);
        System.out.println(s);
        Claims claimByToken = jwtUtils.getClaimByToken(s);
        long userId = Long.parseLong(claimByToken.getSubject());
        System.out.println(userId);
    }
    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
